package com.ciaojian.core.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ciaojian.core.model.ChargeUser;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

/**
 * @author oxiny
 */
public interface ChargeUserMapper extends BaseMapper<ChargeUser> {
    /**
     * 查询用户余额
     *
     * @param userId /
     * @return 余额
     */
    @Select("SELECT balance FROM d_charge_user WHERE user_id = #{userId} ")
    Integer getBalanceByUserId(@Param("userId") Integer userId);

    /**
     * 查询用户冻结余额
     *
     * @param userId /
     * @return /
     */
    @Select("SELECT frozen_balance FROM d_charge_user WHERE user_id = #{userId} ")
    Integer getFrozenBalanceByUserId(@Param("userId") Integer userId);

    /**
     * 查询版本号
     *
     * @param userId 用户ID
     * @return /
     */
    @Select("SELECT version FROM d_charge_user WHERE user_id = #{userId} ")
    Integer getVersionByUserId(@Param("userId") Integer userId);

    /**
     * 更改用户余额
     *
     * @param userId  用户ID
     * @param amount  数额
     * @param dir     方向 0支出 1收入
     * @param version 版本号
     * @return 修改结果
     */
    Boolean change(@Param("userId") Integer userId,
                   @Param("amount") Integer amount,
                   @Param("dir") Integer dir,
                   @Param("version") Integer version);

    /**
     * 更改冻结余额
     *
     * @param userId  用户ID
     * @param amount  数额
     * @param version 版本号
     * @return 修改结果
     */
    @Update("UPDATE d_charge_user " +
            "SET frozen_balance = frozen_balance + #{amount}, " +
            "version = version + 1 " +
            "WHERE user_id = #{userId} " +
            "AND version = #{version} ")
    Boolean frozen(@Param("userId") Integer userId,
                   @Param("amount") Integer amount,
                   @Param("version") Integer version);
}
